from flask import Flask, request, jsonify
import json
from flask_cors import CORS

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app)
import pymysql


class DB:
    def __init__(self):
        self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='1201', db='p9', charset='utf8',
                                    cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def update(self, sql):
        self.cursor.execute(sql)
        self.conn.commit()

    def findone(self, sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res

    def findall(self, sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        return res


db = DB()


@app.route('/')
def hello_world():
    return '牛逼!'


@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql1 = '''select * from ks_users where username = "%s"''' % (data['username'])
        res1 = db.findone(sql1)
        if res1:
            if int(data['password']) == int(res1['password']):
                return jsonify({'code': 200, 'userid': res1['id'], 'ksname': res1['name']})
            else:
                return jsonify({'code': 20010, 'mes': '密码错误'})
        else:
            return jsonify({'code': 20011, 'mes': '账号错误'})
    elif request.method == 'GET':
        userid = int(request.args.get('userid'))
        sql1 = '''select roleid from ks_users where id = %d''' % (userid)
        res1 = db.findone(sql1)
        # print(res1)

        sql2 = '''select z.* from ks_ziyuan as z left join ks_role_ziyuan as rz on rz.ziyuanid = z.id where rz.roleid = %d''' % (
            int(res1['roleid']))
        res2 = db.findall(sql2)
        # print(res2)
        return jsonify({'code': 200, 'list': res2})


import datetime


@app.route('/qingjia', methods=['POST', 'GET'])
def qingjia():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        sql2 = '''select name from ks_users where id = %d''' % (int(data['userid']))
        res2 = db.findone(sql2)
        ctime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
        print(ctime)
        sql1 = '''insert into ks_qj(jia,ctime,next,userid,uname) values(%d,"%s",2,%d,"%s")''' % (
            int(data['jia']), ctime, int(data['userid']), res2['name'])
        db.update(sql1)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql1 = '''select * from ks_qj where type = 1'''
        res1 = db.findall(sql1)

        return jsonify({'code': 200, 'list': res1})


@app.route('/shenpi', methods=['POST', 'GET'])
def shenpi():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if int(data['type']) == 1:
            if int(data['jia']) == 2:
                money = 15000 / 21
                sql1 = '''update ks_qj set type = 2,next = null,money = %d where id = %d''' % (
                    int(money), int(data['id']))
                db.update(sql1)
            else:
                sql1 = '''update ks_qj set type = 2,next = null,money = 0 where id = %d''' % (int(data['id']))
                db.update(sql1)

            return jsonify({'code': 200})
        else:
            sql2 = '''select userid from ks_qj where id = %d''' % (int(data['id']))
            res2 = db.findone(sql2)
            sql2 = '''update ks_qj set type = 3,next = %d, money = 0 where id = %d''' % (
                int(res2['userid']), int(data['id']))
            db.update(sql2)
            return jsonify({'code': 200})





if __name__ == '__main__':
    app.run(debug=True)
